package com.sanqing.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sanqing.bean.Employee;
import com.sanqing.bean.Message;
import com.sanqing.dao.MessageDAO;
import com.sanqing.factory.MessageDAOFactory;

/**
 * Servlet implementation class MsgPublish
 */
@WebServlet("/MsgPublish")
public class MsgPublish extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public MsgPublish() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub

		request.setCharacterEncoding("utf-8");//设置编码格式
		
		//获得jsp中的输入的信息
		String title=request.getParameter("title");
		String content = request.getParameter("content");
		
		//定义跳转实例化对象
		ServletContext servletContext = getServletContext();
		RequestDispatcher dispatcher=null;
		
		//获得session范围employee，确定是那个员工发布消息
		Employee employee = (Employee)request.getSession().getAttribute("employee");
		
		//如果没有获取到employee
		if(employee==null)
		{
			request.setAttribute("error","请先验证身份");
			dispatcher=servletContext.getRequestDispatcher("/View/publicNewMsg.jsp");
		}
		else{
			if(title==null||"".equals(title))
			{
				request.setAttribute("error", "标题不可为空");
				dispatcher=servletContext.getRequestDispatcher("/View/publicNewMsg.jsp");
			}
			else{
				Message message=new Message();//实例化消息对象
				message.setEmployeeID(employee.getEmployeeID());
				message.setMessageTitle(title);
				message.setMessageContent(content);
				message.setPublishTime(new Date());
				//数据库操作
				MessageDAO messageDAO=MessageDAOFactory.getMessageDAOInstance();
				messageDAO.addMessage(message);
				
				//跳转到获取消息列表servlet
				dispatcher=servletContext.getRequestDispatcher("/GetMessageList");
			}
		}
		dispatcher.forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
